<?php

namespace App\Http\Controllers\Purchase;

use App\Http\Controllers\BaseController;
use App\Http\Controllers\Chanjet\TplusCommonController;
use App\Http\Validate\Purchase\PurchaseWarehousingOrder as PurchasePurchaseWarehousingOrder;
use App\Models\Common\EditLog;

use App\Models\Custom\Custom;
use App\Models\Manger\Manger;

use App\Models\Purchase\PurchaseOrder;
use App\Models\Purchase\PurchaseOrderProcess;
use App\Models\Purchase\PurchaseOrderProcessSub;
use App\Models\Purchase\PurchasePreSettleOrder;
use App\Models\Purchase\PurchasePreSettleOrderSub;
use App\Models\Purchase\PurchaseWarehousingOrder;
use App\Models\Purchase\PurchaseWarehousingOrderSub;
use App\Models\Stock\StockSub;
use App\Models\Warehouse\WarehouseList;
use App\Services\Chanjet\ChanjetRequest;
use App\Services\Common\SnCode;
use App\Services\Common\TableExtFeild;
use App\Services\Purchase\PurchaseCommon;
use App\Services\Stock\Stock;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use App\Services\Stock\Stock as StockStock;
use Maatwebsite\Excel\Facades\Excel;
use App\Services\Common\CommonExcelExport;

/**
 * 入库单
 */
class PurchaseWarehousingOrderController extends BaseController
{

    /**
     * 获取表头
     *
     * @param Request $request
     * @return void
     */
    public function gettablefield()
    {
        $cpid = $this->mangerinfo['cpid'];
        $mainextfield = TableExtFeild::getFeildTitle((new PurchaseWarehousingOrder())->getTable(), $cpid);
        $subextfield = TableExtFeild::getFeildTitle((new PurchaseWarehousingOrderSub())->getTable(), $cpid);
        return response()->json(['code' => '000', 'msg' => '获取成功', 'data' => ['mainextfield' => $mainextfield, 'subextfield' => $subextfield]]);
    }

    /**
     * 编辑表头字段
     */
    public function changeorderfield(Request $request)
    {
        $order_id = $request->order_id ?? 0;
        $sub_order_id = $request->sub_order_id ?? 0;
        $cpid = $this->mangerinfo['cpid'];
        $manger_id = $this->mangerinfo['id'];
        $info = PurchaseWarehousingOrder::where(['id' => $order_id, 'manger_id' => $manger_id, 'cpid' => $cpid, 'is_del' => 1])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '无效参数']);
        }
        $suborderinfo = PurchaseWarehousingOrderSub::where(['warehousing_order_id' => $order_id, 'id' => $sub_order_id, 'is_del' => 1])->first();
        $data = TableExtFeild::getTableFeildData($request);
        if ($suborderinfo) {
            PurchaseWarehousingOrderSub::where(['warehousing_order_id' => $order_id, 'id' => $sub_order_id, 'is_del' => 1])->update($data);
        } else {
            PurchaseWarehousingOrder::where(['id' => $order_id, 'manger_id' => $manger_id, 'cpid' => $cpid, 'is_del' => 1])->update($data);
        }
        return response()->json(['code' => '000', 'msg' => '操作成功']);
    }

    /**
     * 入库单列表
     */
    public function getorderlist(Request $request)
    {
        $isgetall = $request->isgetall ?? 0;
        $cpid = $this->mangerinfo['cpid'];
        $manger_id = $this->mangerinfo['id'];
        if ($this->mangerinfo['utype'] == 4 || $this->mangerinfo['utype'] == 3) {
            $manger_id = 0; //查询所有订单
        }
        $list = PurchaseWarehousingOrder::getList($request, $cpid, $manger_id, $isgetall);
        //计算子订单数据到主订单
        $list['list'] = PurchaseCommon::getOrderSum($list['list']);
        return response()->json(['code' => '000', 'msg' => '操作成功', 'data' => $list]);
    }

    /**
     * 获取订单详情
     */
    public function getorderinfo(Request $request)
    {
        $order_id = $request->order_id ?? 0;
        $cpid = $this->mangerinfo['cpid'];
        $manger_id = $this->mangerinfo['id'];
        $query = PurchaseWarehousingOrder::where(['id' => $order_id, 'cpid' => $cpid, 'is_del' => 1])->with(['suborder', 'createmangerinfo','auditmangerinfo','mangerinfo']);
        if ($this->mangerinfo['utype'] == 6) {
            $query->where(['manger_id' => $manger_id]);
        }
        $info = $query->first();

        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '无效参数']);
        }
        $info['sale_order_number'] = '';
        if(isset($info['order_id'])){
            $info['sale_order_number'] = PurchaseOrder::where('id',$info['order_id'])->value('sale_order_number');
        }
        return response()->json(['code' => '000', 'msg' => '操作成功', 'data' => ['info' => $info]]);
    }



    public function getinfobyordersncode(Request $request)
    {
        $warehousing_order_id = $request->warehousing_order_id ?? 0;
        $cpid = $this->mangerinfo['cpid'];
        $manger_id = $this->mangerinfo['id'];
        $query = PurchaseWarehousingOrder::where(['id' => $warehousing_order_id, 'cpid' => $cpid, 'is_del' => 1])->with(['suborder', 'createmangerinfo']);
        if ($this->mangerinfo['utype'] == 6) {
            $query->where(['manger_id' => $manger_id]);
        }
        $info = $query->first();

        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '无效参数']);
        }
        return response()->json(['code' => '000', 'msg' => '操作成功', 'data' => ['info' => $info]]);
    }


    /**
     * 修改订单
     */
    public function dopostedit(Request $request)
    {
        $order_id = $request->order_id ?? 0;
        $cpid = $this->mangerinfo['cpid'];
        $manger_id = $this->mangerinfo['id'];
        $remark = $request->remark ?? '';
        if ($this->mangerinfo['utype'] == 4) {
            $info = PurchaseWarehousingOrder::where(['id' => $order_id,  'cpid' => $cpid, 'is_del' => 1])->with('suborder')->first();
        } else {
            $info = PurchaseWarehousingOrder::where(['id' => $order_id, 'manger_id' => $manger_id, 'cpid' => $cpid, 'is_del' => 1])->with('suborder')->first();
        }
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '无效参数']);
        }

        if ($this->mangerinfo['utype'] == 6 && $info->is_finance_update != 1) {
            return response()->json(['code' => '001', 'msg' => '财务修改后，采购不可修改']);
        }

        if ($info->create_status == 2) {
            return response()->json(['code' => '001', 'msg' => '已生成订单不可修改']);
        }
        //修改的信息只可修改子订单信息

        //判断是否完结
        $finishcount = PurchaseOrderProcess::where(['order_id' => $info->order_id,  'cpid' => $cpid, 'is_del' => 1, 'is_finish' => 2])->count();
        if ($finishcount > 0) {
            return response()->json(['code' => '001', 'msg' => '订单已完结，不可修改']);
        }

        $suborder = is_array($request->suborder) ? $request->suborder : (is_array(json_decode($request->suborder, true)) ? json_decode($request->suborder, true) : []);
        if (count($suborder) <= 0) {
            return response()->json(['code' => '001', 'msg' => '订单数据不能为空']);
        }
        $cpid = $this->mangerinfo['cpid'];
        $ValidateSub = new PurchasePurchaseWarehousingOrder();
        $suborderdata = [];
        $order_weight = 0;
        $order_count = 0;
        $order_money = 0;
        $order_weight_old = 0;
        $order_count_old = 0;
        $order_money_old = 0;
        $suborderkey = [];
        foreach ($suborder as $s_order) {
            $s_order = is_array($s_order) ? $s_order : json_decode($s_order, true);
            if (!$ValidateSub->check($s_order)) { //初筛过滤
                return response()->json(['code' => '001', 'msg' => $ValidateSub->getError()]);
            }
            //判断子订单是否存在
            $suborderinfo = PurchaseWarehousingOrderSub::where(['cpid' => $cpid, 'warehousing_order_id' => $order_id, 'id' => $s_order['id'], 'is_del' => 1])->first();
            if (!$suborderinfo || $s_order['stock_id'] != $suborderinfo->stock_id) { //只可修改件数，重量等相关数据
                return response()->json(['code' => '001', 'msg' => '无效参数!']);
            }
            $suborderinfo = $suborderinfo->toArray();
            /***
             * 此处取得子订单，单重/总重 model取数据自动/10，需要*10
             *
            */
            $suborderinfo['total_weight'] = mathfuncweight('mul', $suborderinfo['total_weight'], 10); //kg*10
            $suborderinfo['weight'] = mathfuncweight('mul', $suborderinfo['weight'], 10); //kg*10

            $order_weight_old = mathfuncweight('add', $order_weight_old, $suborderinfo['total_weight']); //kg*10
            $order_count_old = mathfunc('add', $order_count_old, $suborderinfo['count']);
            $order_money_old = mathfuncmoney('add', $order_money_old, intval($suborderinfo['total_money']));

            $suborderkey[] = $suborderinfo['id'];
            // if ($suborderinfo['create_status'] != 1) { //如已生成则不可修改数据跳过
            //     $order_weight = mathfunc('add', $order_weight, $suborderinfo['total_weight']);
            //     $order_count = mathfunc('add', $order_count, $suborderinfo['count']);
            //     $order_money = mathfunc('add', $order_money, intval($suborderinfo['total_money']));
            //     continue;
            // }

            $sub_sub_order = isset($s_order['sub_sub_order']) ? (is_array($s_order['sub_sub_order']) ? $s_order['sub_sub_order'] : (is_array(json_decode($s_order['sub_sub_order'], true)) ? json_decode($s_order['sub_sub_order'], true) : [])) : [];

            /***
             * 此处$sub_sub_order，前端传入，数据不对。单重对，总重不对
             *  分别在 定尺、过磅、理记处理
             *  定尺 单重*件数=总重
             *  过磅 取数据库总重
             *  理记 宽*高*长=单重 * 件数=总重
             *
             * 在下边钢材类型判定，处理
             *
             */


            $update_item = [];
            // if ($suborderinfo['archive_type'] == 1) { //理计
            //     $lengthwithcount = isset($s_order['lengthwithcount']) ? (is_array($s_order['lengthwithcount']) ? $s_order['lengthwithcount'] : (is_array(json_decode($s_order['lengthwithcount'], true)) ? json_decode($s_order['lengthwithcount'], true) : [])) : [];


            //     //计算重量
            //     $length_count = 0;
            //     $total_weight = 0;
            //     foreach ($lengthwithcount as &$lengthval) {
            //         $length = $lengthval['length'];
            //         $count = $lengthval['count'];
            //         $length_count = bcadd($length_count, $count);
            //         $weight = mathtoweightbyarchivetype($suborderinfo['archive_spec'], $suborderinfo['archive_type'], $length); //kg
            //         $total_weight = mathfuncweight('add', $total_weight, mathfuncweight('mul', mathfuncweight('mul', $weight, 10), $count)); //kg*10

            //         $lengthval['total_weight'] = mathfuncweight('mul', mathfuncweight('mul', $weight, 10), $count);
            //     }
            //     if ($length_count != $s_order['count']) {
            //         return response()->json(['code' => '001', 'msg' => '长度件数不匹配']);
            //     }
            //     $update_item['oldlengthwithcount'] = $suborderinfo['lengthwithcount']; //记录旧信息
            //     $update_item['lengthwithcount'] = json_encode($lengthwithcount);
            //     $update_item['total_weight'] = $total_weight; //kg*10
            //     $update_item['count'] = $s_order['count'];
            //     $update_item['weight'] = mathfuncweight('div', $update_item['total_weight'], $s_order['count']); //kg*10
            // } elseif ($suborderinfo['archive_type'] == 2) { //过磅，取总重和件数
            //     $total_weight = $s_order['total_weight'];
            //     $update_item['total_weight'] = mathfuncweight('mul', $total_weight, 10); //kg*10
            //     $update_item['count'] = $s_order['count'];
            //     $update_item['weight'] = mathfuncweight('div', $s_order['total_weight'], $s_order['count']); //kg*10
            // } elseif ($suborderinfo['archive_type'] == 3) { //定尺，
            //     $suborderinfo['weight'] = mathfuncweight('mul', $suborderinfo['weight'], 10); //kg*10
            //     $total_weight = intval(mathfuncweight('mul', $suborderinfo['weight'], $s_order['count'])); //kg*10
            //     $update_item['total_weight'] = $total_weight;
            //     $update_item['count'] = $s_order['count'];
            //     $update_item['weight'] = $suborderinfo['weight']; //kg*10
            // }

            if ($suborderinfo['archive_type'] == 1) { //理计

                //计算重量
                $length_count = 0;
                $total_weight = 0;
                foreach ($sub_sub_order as &$subsubval) {
                    if (
                        $subsubval['length'] <= 0 || $subsubval['count'] <= 0 || $subsubval['stock_num'] == ''
                        || $subsubval['origin'] == ''  || $subsubval['layer_num'] == ''
                    ) {
                        return response()->json(['code' => '001', 'msg' => '理计码单信息有误']);
                    }



                    $length = $subsubval['length'];
                    $count = $subsubval['count'];
                    $length_count = bcadd($length_count, $count);
                    $weight = mathtoweightbyarchivetype($suborderinfo['archive_spec'], $suborderinfo['archive_type'], $length); //kg
                    $total_weight = mathfuncweight('add', $total_weight, mathfuncweight('mul', mathfuncweight('mul', $weight, 10), $count)); //kg*10
                    $subsubval['weight'] = mathfuncweight('mul', $weight, 10);
                    $subsubval['total_weight'] = mathfuncweight('mul', mathfuncweight('mul', $weight, 10), $count);
                    $subsubval['total_money'] = mathfuncmoney('mul', mathfuncweight('div', $subsubval['total_weight'], 10000, 4), $suborderinfo['price'], 0);
                }
                if ($length_count != $s_order['count']) {
                    return response()->json(['code' => '001', 'msg' => '理计码单长度件数不匹配']);
                }



                // $update_item['oldlengthwithcount'] = $suborderinfo['sub_sub_order']; //记录旧信息
                $update_item['sub_sub_order'] = json_encode($sub_sub_order);//此处前端传入错误总重/总金额，已经修正
                $update_item['total_weight'] = $total_weight; //kg*10
                $update_item['count'] = $s_order['count'];
                $update_item['weight'] = mathfuncweight('div', $update_item['total_weight'], $s_order['count']); //kg*10
            }

            if ($suborderinfo['archive_type'] == 3) {


                $length_count = 0;
                foreach ($sub_sub_order as &$subsubval) {
                    if (
                        $subsubval['count'] <= 0 || $subsubval['stock_num'] == ''
                        || $subsubval['origin'] == ''  || $subsubval['layer_num'] == ''
                    ) {
                        return response()->json(['code' => '001', 'msg' => '定尺码单信息有误']);
                    }



                    $count = $subsubval['count'];
                    $length_count = bcadd($length_count, $count);
                    //此处无需*10，数据来自数据库
                    $subsubval['weight'] = mathfuncweight('mul', $suborderinfo['weight'], 1); //kg*10
                    $subsubval['total_weight'] = intval(mathfuncweight('mul', $suborderinfo['weight'], $subsubval['count']));
                    $subsubval['total_money'] = mathfuncmoney('mul', mathfuncweight('div', $subsubval['total_weight'], 10000, 4), $suborderinfo['price'], 1);
                }
                if ($length_count != $s_order['count']) {
                    return response()->json(['code' => '001', 'msg' => '定尺码单入库件数不匹配']);
                }



                $total_weight = intval(mathfuncweight('mul', $suborderinfo['weight'], $s_order['count']));
                $update_item['total_weight'] = $total_weight;
                $update_item['count'] = $s_order['count'];
                $update_item['weight'] = $suborderinfo['weight']; //kg*10
                // $update_item['oldlengthwithcount'] = $suborderinfo['sub_sub_order']; //记录旧信息



                $update_item['sub_sub_order'] = json_encode($sub_sub_order);//此处前端传入错误 总重/总金额，已经修正
            }

            if ($suborderinfo['archive_type'] == 2) { //过磅


                //计算重量
                $length_count = 0;
                $total_weight = 0;
                foreach ($sub_sub_order as &$subsubval) {
                    if (
                        $subsubval['count'] <= 0 || $subsubval['stock_num'] == ''
                        || $subsubval['origin'] == ''  || $subsubval['layer_num'] == '' || $subsubval['total_weight'] <= 0
                    ) {
                        return response()->json(['code' => '001', 'msg' => '过磅码单信息有误']);
                    }
                    $subsubval['length'] = isset($subsubval['length']) ? $subsubval['length'] : 0;

                    //$subsubval['total_weight'] = mathfuncweight('mul', $subsubval['total_weight'], 10); //kg*10  。孙级别总重，输入，需要验证是否正确，前端传入错误，需要除以10000
                    //修正前端传入错误，获取总重。单位 g
                    //$subsubval['total_weight'] = mathfuncweight('div',$subsubval['total_weight'],10000,0);
                    $subsubval['total_weight'] = $subsubval['total_weight'];//孙订单重量 单位：g,前端传入

                    //修正前端传入错误，获取单重。单位 g
                    //$subsubval['weight'] = intval(mathfuncweight('div', $subsubval['total_weight'], $subsubval['count']));
                    $subsubval['weight'] = mathfuncweight('div', $subsubval['total_weight'], $subsubval['count']);

                    $subsubval['total_money'] = mathfuncmoney('mul', mathfuncweight('div', $subsubval['total_weight'], 10000, 4), $suborderinfo['price'], 0);
                }

                //此处总重，前端传入的，单位是 kg,需要*10。数据正常情况，不会出现小数
                $total_weight = $s_order['total_weight'];
                $update_item['total_weight'] = mathfuncweight('mul', $total_weight, 10); //kg*10
                $update_item['count'] = $s_order['count'];
                $update_item['weight'] = mathfuncweight('div', ($s_order['total_weight'] *10), $s_order['count']); //kg*10


                $update_item['sub_sub_order'] = json_encode($sub_sub_order);

                //为了正确计算,过磅，子订单金额，重量必须 g 为单位
                $total_weight = $update_item['total_weight'];
            }


            $update_item['total_money'] = mathfuncmoney('mul', mathfuncweight('div', $total_weight, 10000, 4), $suborderinfo['price'], 0);

            $update_item['changedata'] = [
                'total_money' => mathfuncmoney('sub', $update_item['total_money'], $suborderinfo['total_money']),
                'count' => mathfunc('sub', $update_item['count'], $suborderinfo['count']),
                'total_weight' => mathfuncweight('sub', $update_item['total_weight'], $suborderinfo['total_weight'])
            ];
            $order_weight = mathfuncweight('add', $order_weight, $update_item['total_weight']);
            $order_count = mathfunc('add', $order_count, $update_item['count']);
            $order_money = mathfuncmoney('add', $order_money, intval($update_item['total_money']));
            $update_item['sub_order_id'] = $suborderinfo['sub_order_id'];

            $update_item['stock_id'] = $suborderinfo['stock_id'];
            $suborderdata[$suborderinfo['id']] = $update_item;
        }
        // print_r($suborderdata);exit;
        DB::beginTransaction();
        try {
            foreach ($suborderdata as $key => $val) {
                Stock::doStockIn($cpid, $val['stock_id'], $val['changedata']['count'], $val['changedata']['total_weight']);

                // PurchaseOrderProcessSub::where(['cpid' => $cpid, 'sub_order_id' => $val['sub_order_id']])->update(
                //     [
                //         'warehousing_weight' => DB::raw('warehousing_weight + ' . $val['changedata']['total_weight']),
                //         'warehousing_count' => DB::raw('warehousing_count + ' . $val['changedata']['count']),
                //         'warehousing_money' => DB::raw('warehousing_money + ' . $val['changedata']['total_money'])
                //     ]
                // );
                unset($val['changedata']);
                unset($val['sub_order_id']);
                // //处理库存和子库存相关，库存和子库存分开计算

                // //处理待入库相关数据
                // if(isset($val['lengthwithcount']) && isset($val['oldlengthwithcount'])){
                //     $lengthwithcount=json_decode($val['lengthwithcount'],true);
                //     foreach($lengthwithcount as $substock){
                //         Stock::doStockInSub($cpid,$val['stock_id'],$substock['count'],$substock['total_weight'],1,$substock['length']);
                //     }

                //     $oldlengthwithcount=json_decode($val['oldlengthwithcount'],true);

                //     foreach($oldlengthwithcount as $oldsubstock){
                //         Stock::doStockInSub($cpid,$val['stock_id'],-$oldsubstock['count'],-$oldsubstock['total_weight'],1,$oldsubstock['length']);
                //     }
                //     unset($val['oldlengthwithcount']);
                // }
                PurchaseWarehousingOrderSub::where(['cpid' => $cpid, 'warehousing_order_id' => $order_id, 'id' => $key])->update($val);
            }


            /**
             * 处理订单进度
             */

            // PurchaseOrderProcess::where(['cpid' => $cpid, 'order_id' => $info->order_id])->update([
            //     'warehousing_weight' => DB::raw('warehousing_weight + ' . mathfuncweight('sub', $order_weight, $order_weight_old)),
            //     'warehousing_count' => DB::raw('warehousing_count + ' . mathfunc('sub', $order_count, $order_count_old)),
            //     'warehousing_money' => DB::raw('warehousing_money + ' . mathfuncmoney('sub', $order_money, $order_money_old))
            // ]);

            if ($this->mangerinfo['utype'] == 4) { //财务修改

                PurchaseWarehousingOrder::where(['id' => $order_id, 'cpid' => $cpid, 'is_del' => 1])->update(['is_finance_update' => 2, 'remark' => $remark, 'update_at' => time()]);
            } else {
                PurchaseWarehousingOrder::where(['id' => $order_id, 'manger_id' => $manger_id, 'cpid' => $cpid, 'is_del' => 1])->update(['remark' => $remark, 'update_at' => time()]);
            }


            $editlog = ['cpid' => $cpid, 'order_type' => 3, 'order_sn_code' => $info->order_sn_code, 'before_data' => json_encode($info), 'editor_mid' => $this->mangerinfo['id'], 'editor_realname' => $this->mangerinfo['realname'], 'create_at' => time()];
            $editlog['after_data'] = json_encode(PurchaseWarehousingOrder::where(['id' => $order_id, 'cpid' => $cpid, 'is_del' => 1])->with('suborder')->first());
            EditLog::create($editlog);

            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            Log::error('采购订单修改失败' . $e->getMessage());
            return response()->json(['code' => '001', 'msg' => '采购订编辑失败' . $e->getMessage()]);
        }

        return response()->json(['code' => '000', 'msg' => '操作成功']);
    }

    /**
     * 撤销审核
     */
    public function docancelorderaudit(Request $request)
    {
        $order_id = $request->order_id ?? 0;
        $cpid = $this->mangerinfo['cpid'];
        $manger_id = $this->mangerinfo['id'];
        $info = PurchaseWarehousingOrder::where(['id' => $order_id, 'manger_id' => $manger_id, 'cpid' => $cpid, 'is_del' => 1])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '无效参数']);
        }



        if ($info->audit_status != 3) {
            return response()->json(['code' => '001', 'msg' => '只有审核成功的才可以撤销审核']);
        }

        if ($info->create_status != 1) {
            return response()->json(['code' => '001', 'msg' => '已生成订单无法撤销']);
        }

        if ($info->is_from_sale == 2) {

            return response()->json(['code' => '001', 'msg' => '以销定采订单不可撤销']);
        }


        //判断是否完结
        $finishcount = PurchaseOrderProcess::where(['order_id' => $info->order_id,  'cpid' => $cpid, 'is_del' => 1, 'is_finish' => 2])->count();
        if ($finishcount > 0) {
            return response()->json(['code' => '001', 'msg' => '订单已完结，不可撤销审核']);
        }


        //处理库存相关

        //处理采购订单执行情况相关


        DB::beginTransaction();
        try {

            if($info->audit_status == 3){
                $suborder = $info->suborder()->where(['is_del' => 1])->get()->toArray();

                StockSub::where(['cpid' => $cpid,'wo_order_sn_code' => $info->order_sn_code])->delete();
                $warehousing_weight = 0;
                $warehousing_count = 0;
                $warehousing_money = 0;
                foreach ($suborder as $subval) {
                    //更新主库存
                    StockStock::doStockIn($cpid, $subval['stock_id'], -$subval['count'], -$subval['total_weight']*10, 2);

                    //更新订单执行情况
                    PurchaseOrderProcessSub::where([['cpid', $cpid], ['sub_order_id', $subval['sub_order_id']]])
                        ->update([
                            'warehousing_weight' => DB::raw('warehousing_weight - ' . $subval['total_weight'] * 10),
                            'warehousing_count' => DB::raw('warehousing_count - ' . $subval['count']),
                            'warehousing_money' => DB::raw('warehousing_money - ' . $subval['total_money'])
                        ]);
                    //执行情况
                    $warehousing_weight = mathfuncweight('add', $warehousing_weight, $subval['total_weight']);
                    $warehousing_count = mathfunc('add', $warehousing_count, $subval['count']);
                    $warehousing_money = mathfuncmoney('add', $warehousing_money, $subval['total_money']);
                }
                PurchaseOrderProcess::where([['order_id',  $info->order_id], ['cpid', $cpid]])
                    ->update([
                        'warehousing_weight' => DB::raw('warehousing_weight - ' . $warehousing_weight * 10),
                        'warehousing_count' => DB::raw('warehousing_count - ' . $warehousing_count),
                        'warehousing_money' => DB::raw('warehousing_money - ' . $warehousing_money)
                    ]);

            }

            PurchasePreSettleOrder::where(['warehousing_order_id' => $order_id,  'cpid' => $cpid, 'is_del' => 1])->update(['is_del' => 2, 'del_at' => time()]);
            PurchaseWarehousingOrder::where(['id' => $order_id,  'cpid' => $cpid, 'is_del' => 1])->update(['audit_status' => 1,'audit_at'=>0,'audit_manger_id'=>0, 'update_at' => time()]);

            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();

            return response()->json(['code' => '001', 'msg' => '入库撤审操作失败' . $e->getMessage()]);
        }



        //进货单删除
        $Chanjet_param = [
            "param" => [
                //"ExternalCode" => $info->po_order_sn_code.'||'.$info->order_sn_code
                "voucherCode" => $info->order_sn_code.'|'.$info->id
            ]
        ];
        $start_block = microtime(true);
        if (TplusCommonController::isAllowRequestTplus($this->mangerinfo)) {
            ChanjetRequest::getInstance()->PurchaseArrivalOpenApiDelete($Chanjet_param, $this->mangerinfo['org_id']);
        }
        $time_block = microtime(true)- $start_block;
        Log::info("删除进货单,time: ".$time_block);
        return response()->json(['code' => '000', 'msg' => '操作成功']);
    }

    /**
     * 入库单审核_提交审核
     */
    public function doorderaudit(Request $request)
    {
        $order_id = $request->order_id ?? 0;
        $cpid = $this->mangerinfo['cpid'];
        $manger_id = $this->mangerinfo['id'];
        $info = PurchaseWarehousingOrder::where(['id' => $order_id, 'manger_id' => $manger_id, 'cpid' => $cpid, 'is_del' => 1])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '无效参数']);
        }
        if ($info->audit_status != 1 && $info->audit_status != 4) {
            return response()->json(['code' => '001', 'msg' => '只有未审核的才可以提交审核']);
        }

        //判断是否完结
        $finishcount = PurchaseOrderProcess::where(['order_id' => $info->order_id,  'cpid' => $cpid, 'is_del' => 1, 'is_finish' => 2])->count();
        if ($finishcount > 0) {
            return response()->json(['code' => '001', 'msg' => '订单已完结，不可提交审核']);
        }

        PurchaseWarehousingOrder::where(['id' => $order_id, 'manger_id' => $manger_id, 'cpid' => $cpid, 'is_del' => 1])->update(['audit_status' => 2, 'update_at' => time()]);

        return response()->json(['code' => '000', 'msg' => '操作成功']);
    }

    /**
     * 财务审核
     * 审核通过后，已入库，未通过审核或未审核是待入库
     *
     * 已销定采，采购入库审批 通过后
     * 采购流完成，可以执行 销售流
     *
     *
     *
     *
     */
    public function doorderauditbyfinance(Request $request)
    {
        $order_id = $request->order_id ?? 0;
        $cpid = $this->mangerinfo['cpid'];
        $info = PurchaseWarehousingOrder::where(['id' => $order_id,  'cpid' => $cpid, 'is_del' => 1])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '无效参数']);
        }
        if ($info->audit_status != 2) {
            return response()->json(['code' => '001', 'msg' => '只有待审核的才可以进行审核操作']);
        }
        $audit_status = $request->audit_status ?? 0;
        if (!in_array($audit_status, [3, 4])) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }
        //判断是否完结
        $finishcount = PurchaseOrderProcess::where(['order_id' => $info->order_id,  'cpid' => $cpid, 'is_del' => 1, 'is_finish' => 2])->count();
        if ($finishcount > 0) {
            return response()->json(['code' => '001', 'msg' => '订单已完结，不可进行审核操作']);
        }

        $Chanjet_VoucherDetails = [];//单据明细
        //子订单入库
        DB::beginTransaction();
        try {
            if($audit_status == 3){
                $purchaseOrder = PurchaseOrder::where('id',$info->order_id)->first();
                if($purchaseOrder->is_from_sale == '2'){
                    PurchaseOrder::where('id',$info->order_id)->update(
                        [
                            'is_finish' => '2',
                            'update_at' => time()
                        ]
                    );
                }

                $suborder = $info->suborder()->where(['is_del' => 1])->get()->toArray();
                $ins_data = [];
                $warehousing_weight = 0;
                $warehousing_count = 0;
                $warehousing_money = 0;
                foreach ($suborder as $subval) {
                    $subSubOrders = $subval['sub_sub_order'];
                    foreach ($subSubOrders as &$subsubval) {
                        $item = [
                            'cpid' => $cpid,
                            'stock_id' => $subval['stock_id'],
                            'length' => $subsubval['length'],
                            'weight' => $subsubval['weight'],
                            // 'count'=>$subsubval['count'],
                            'total_weight' => $subsubval['total_weight'],
                            'can_use_weight' => $subsubval['total_weight'],
                            'can_use_pieces' => $subsubval['count'],
                            'current_pieces' => $subsubval['count'],
                            'current_weight' => $subsubval['total_weight'],
                            'warehousing_at' => time(),
                            'stock_num' => $subsubval['stock_num'],
                            'origin' => $subsubval['origin'],
                            'layer_num' => $subsubval['layer_num'],
                            'price' => $subsubval['price'],
                            'total_money' => $subsubval['total_money'],
                            'warehouse_name' => $subval['warehouse_name'],
                            'archive_no' => $subval['archive_no'],
                            'archive_name' => $subval['archive_name'],
                            'archive_spec' => $subval['archive_spec'],
                            'archive_material' => $subval['archive_material'],
                            'steel_factory_name' => $subval['steel_factory_name'],
                            'breed_name' => $subval['breed_name'],
                            'archive_type' => $subval['archive_type'],
                            'manger_id' => $info->manger_id,
                            'pa_id' => $info->pa_id,
                            'pa_type' => $info->pa_type,
                            'contract_no' => $info->pa_contract_no,
                            'carship_no' => $info->carship_no,
                            'remark' => $subsubval['remark'],
                            'wo_order_sn_code' => $info->order_sn_code
                        ];
                        $subsubval['warehousing_at'] = time();
                        $ins_data[] = $item;
                    }
                    $Chanjet_VoucherDetails [] = [
                        "Inventory" => ["Code" => $subval['archive_no']],
                        "Warehouse" => ["Code" => WarehouseList::where(['warehouse_name' => $subval['warehouse_name'], 'cpid' => $cpid])->value('warehouse_no')],
                        "Unit" => ["Name" => "吨"],
                        "Unit2" => ["Name" => "件"],
                        "TaxRate" =>"0",//税率
                        "Quantity" => strval(bcdiv($subval['total_weight'],'1000',3)),//重量
                        "Quantity2" => $subval['count'],//件数

                        "OrigTaxAmount" => $subval['total_money']/100,
                        "OrigDiscountAmount" => $subval['total_money']/100,
                        "DynamicPropertyKeys" => ['pubuserdefnvc1','pubuserdefnvc2','pubuserdefnvc3'],
                        "DynamicPropertyValues" => [$subval['steel_factory_name'],$subval['breed_name'],$subval['archive_material']],
                    ];
                    //更新主库存
                    StockStock::doStockIn($cpid, $subval['stock_id'], $subval['count'], $subval['total_weight']*10, 2);
                    // 更新主表单字段
                    PurchaseWarehousingOrderSub::where(['id' => $subval['id']])
                        ->update([
                            'sub_sub_order' => json_encode($subSubOrders)
                        ]);

                    //更新订单执行情况
                    PurchaseOrderProcessSub::where([['cpid', $cpid], ['sub_order_id', $subval['sub_order_id']]])
                        ->update([
                            'warehousing_weight' => DB::raw('warehousing_weight + ' . $subval['total_weight'] * 10),
                            'warehousing_count' => DB::raw('warehousing_count + ' . $subval['count']),
                            'warehousing_money' => DB::raw('warehousing_money + ' . $subval['total_money']),
                        ]);
                    //执行情况
                    $warehousing_weight = mathfuncweight('add', $warehousing_weight, $subval['total_weight']);
                    $warehousing_count = mathfunc('add', $warehousing_count, $subval['count']);
                    $warehousing_money = mathfuncmoney('add', $warehousing_money, $subval['total_money']);
                }

                StockSub::insert($ins_data); //子库存写入

                PurchaseOrderProcess::where([['order_id',  $info->order_id], ['cpid', $cpid]])
                    ->update([
                        'warehousing_weight' => DB::raw('warehousing_weight + ' . $warehousing_weight * 10),
                        'warehousing_count' => DB::raw('warehousing_count + ' . $warehousing_count),
                        'warehousing_money' => DB::raw('warehousing_money + ' . $warehousing_money)
                    ]);

            }

            PurchaseWarehousingOrder::where(['id' => $order_id,  'cpid' => $cpid, 'is_del' => 1])->update(['audit_status' => $audit_status,"audit_at"=>time(),'audit_manger_id'=>$this->mangerinfo['id'], 'update_at' => time()]);

            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();

            return response()->json(['code' => '001', 'msg' => '入库审核失败' . $e->getMessage()]);
        }
        /***
         *  采购入库单入库 统审通过后,T+同步销货单 2025.02.08
         *
         */
        if($audit_status == 3){
            $Chanjet_param = [
                "dto" => [
                    "ExternalCode" => $info->po_order_sn_code ."|". $info->order_sn_code,//外部单据编号
                    "IsModifiedCode" => "true",
                    "Code" => $info->order_sn_code.'|'.$info->id,
                    "VoucherDate" => date('Y-m-d'),//单据日期
                    "BusinessType" => ["Code"=>"01"],//01--普通采购 02--采购退货
                    "Partner" => [
                        "Code" => Custom::where('id', $info['custom_id'])->value("company_code"),
                        "Name" => Custom::where('id', $info['custom_id'])->value("company_name"),
                    ],
                    "Warehouse" => ["Code" => $Chanjet_VoucherDetails[0]['Warehouse']['Code']],//仓库编码
                    "InvoiceType" => ["Code"=>$info->invoice_type== '1'?'00':'09'],//00--专票  09--普通发票
                    "VoucherDetails" => $Chanjet_VoucherDetails,
                ]
            ];
            if($info->carship_no){
                $Chanjet_param["dto"]["DynamicPropertyKeys"] = ["pubuserdefnvc1"];
                $Chanjet_param["dto"]["DynamicPropertyValues"] = [$info->carship_no];
            }
            if(!empty($info->manger_id)){
                $Chanjet_param['dto']['Department'] = ["Code" => Manger::where('id',$info->manger_id)->value('sys_dpm_id')];//部门编码
                $Chanjet_param['dto']['Clerk'] = ["Code" => Manger::where('id',$info->manger_id)->value('code_no')];//业务员编码
            }
            $requestData = [
                "api" => "purchaseArrivalCreate",
                "param" => $Chanjet_param,
                "mangerinfo" => $this->mangerinfo
            ];
            \App\Jobs\Purchase::dispatch($requestData);
//            //进货单
//            if (TplusCommonController::isAllowRequestTplus($this->mangerinfo)) {
//                ChanjetRequest::getInstance()->purchaseArrivalCreate($Chanjet_param, $this->mangerinfo['org_id']);
//            }
        }

        return response()->json(['code' => '000', 'msg' => '操作成功']);
    }


    /**
     * 批量生成预结算单
     */

    public function createsettleorder(Request $request)
    {
        $order_id_arr = $request->order_id_arr ?? [];
        $cpid = $this->mangerinfo['cpid'];
        $manger_id = $this->mangerinfo['id'];
        $order_id_arr = is_array($order_id_arr) ? $order_id_arr : (is_array(json_decode($order_id_arr, true)) ? json_decode($order_id_arr, true) : []);
        if (count($order_id_arr) <= 0) {
            return response()->json(['code' => '001', 'msg' => '无效参数']);
        }
        $count = PurchaseWarehousingOrder::where(['manger_id' => $manger_id, 'cpid' => $cpid, 'is_del' => 1, 'create_status' => 1, 'audit_status' => 3, 'settle_model' => 3])->whereIn('id', $order_id_arr)->count();
        if ($count != count($order_id_arr)) {
            return response()->json(['code' => '001', 'msg' => '后结算且审核通过的入库单方可生成预结算单']);
        }

        //批量生成
        $orderlist = PurchaseWarehousingOrder::with('suborder')->where(['manger_id' => $manger_id, 'cpid' => $cpid, 'is_del' => 1, 'create_status' => 1, 'audit_status' => 3, 'settle_model' => 3])->whereIn('id', $order_id_arr)->get()->toArray();


        DB::beginTransaction();
        try {

            foreach ($orderlist as $order) {
                //判断是否完结
                $finishcount = PurchaseOrderProcess::where(['order_id' => $order['order_id'],  'cpid' => $cpid, 'is_del' => 1, 'is_finish' => 2])->count();
                if ($finishcount > 0) {
                    return response()->json(['code' => '001', 'msg' => '订单已完结，不可撤销审核']);
                }
                $maindata = [
                    'cpid' => $order['cpid'],
                    'order_id' => $order['order_id'],
                    'stockin_order_id' => $order['stockin_order_id'],
                    'warehousing_order_id' => $order['id'],
                    'manger_id' => $order['manger_id'],
                    'pa_id' => $order['pa_id'],
                    'pa_type' => $order['pa_type'],
                    'custom_id' => $order['custom_id'],
                    'company_name' => $order['company_name'],
                    'pa_contract_no' => $order['pa_contract_no'],
                    'pa_sn_code' => $order['pa_sn_code'],
                    'pa_settle_company_name' => $order['pa_settle_company_name'],
                    'sales_manger_id' => $order['sales_manger_id'],
                    'sales_manger_name' => $order['sales_manger_name'],
                    'order_date' => $order['order_date'],
                    'settle_model' => $order['settle_model'],
                    'invoice_type' => $order['invoice_type'],
                    'carship_no' => $order['carship_no'],
                    'po_order_sn_code' => $order['po_order_sn_code'],
                    'order_sn_code' => SnCode::getSnCode('PPSO_'),
                    'settle_model_start_time' => $order['settle_model_start_time'],
                    'settle_model_end_time' => $order['settle_model_end_time'],
                    'remark' => $order['remark'],
                    'create_at' => time(),
                    'update_at' => time()
                ];
                $pre_settle_order_id = PurchasePreSettleOrder::create($maindata)->id;

                $suborderdata = [];
                foreach ($order['suborder'] as $suborder) {
                    $item = [
                        'cpid' => $suborder['cpid'],
                        'pre_settle_order_id' => $pre_settle_order_id,
                        'sub_order_id' => $suborder['sub_order_id'],
                        'stock_id' => $suborder['stock_id'],
                        'count' => $suborder['count'],
                        'weight' => mathfuncweight('mul', $suborder['weight'], 10),
                        'total_weight' => mathfuncweight('mul', $suborder['total_weight'], 10),
                        'price' => $suborder['price'],
                        'base_price' => $suborder['base_price'],
                        'add_price' => $suborder['add_price'],
                        'total_money' => $suborder['total_money'],
                        'sub_sub_order' => json_encode($suborder['sub_sub_order']),
                        'warehouse_name' => $suborder['warehouse_name'],
                        'archive_no' => $suborder['archive_no'],
                        'archive_name' => $suborder['archive_name'],
                        'archive_spec' => $suborder['archive_spec'],
                        'archive_material' => $suborder['archive_material'],
                        'steel_factory_name' => $suborder['steel_factory_name'],
                        'breed_name' => $suborder['breed_name'],
                        'archive_type' => $suborder['archive_type'],
                    ];
                    $suborderdata[] = $item;
                }
                PurchasePreSettleOrderSub::insert($suborderdata);
            }

            PurchaseWarehousingOrder::where(['manger_id' => $manger_id, 'cpid' => $cpid, 'is_del' => 1, 'create_status' => 1, 'audit_status' => 3, 'settle_model' => 3])
                ->whereIn('id', $order_id_arr)->update(['create_status' => 2, 'createorder_at' => time()]);
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['code' => '001', 'msg' => '生成结算单失败' . $e->getMessage()]);
        }
        return response()->json(['code' => '000', 'msg' => '操作成功']);
    }

    /**
     * 确认收票
     */
    public function doorderinvoiceconfirm(Request $request)
    {
        $order_id = $request->order_id ?? 0;
        $sub_order_id = $request->sub_order_id ?? 0;
        $cpid = $this->mangerinfo['cpid'];
        $manger_id = $this->mangerinfo['id'];
        $query = PurchaseWarehousingOrder::where(['id' => $order_id, 'cpid' => $cpid, 'is_del' => 1]);
        if ($this->mangerinfo['utype'] == 6) {
            $query->where(['manger_id' => $manger_id]);
        }
        $info = $query->first();

        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '无效参数1']);
        }

        $subinfo = PurchaseWarehousingOrderSub::where(['id' => $sub_order_id, 'cpid' => $cpid, 'is_del' => 1, 'warehousing_order_id' => $order_id])->first();

        if (!$subinfo) {
            return response()->json(['code' => '001', 'msg' => '无效参数2']);
        }
        $invoice_confirm = $request->invoice_confirm ?? 0;

        if (!in_array($invoice_confirm, [1, 2])) {
            return response()->json(['code' => '001', 'msg' => '无效参数3']);
        }



        PurchaseWarehousingOrderSub::where(['id' => $sub_order_id, 'cpid' => $cpid, 'is_del' => 1, 'warehousing_order_id' => $order_id])->update(['invoice_confirm' => $invoice_confirm, 'invoice_confirm_at' => time()]);



        return response()->json(['code' => '000', 'msg' => '操作成功']);
    }

    ///
    public function doorderexport(Request $request)
    {
        $isgetall = 1;
        $cpid = $this->mangerinfo['cpid'];
        $manger_id = $this->mangerinfo['id'];
        if ($this->mangerinfo['utype'] == 4 || $this->mangerinfo['utype'] == 3) {
            $manger_id = 0; //查询所有订单
        }
        $list = PurchaseWarehousingOrder::getList($request, $cpid, $manger_id, $isgetall);

        $exceldata = [];
        $row = [
            [
                'keynum' => '序号',
                'po_order_sn_code' => '采购订单号',
                'order_sn_code' => '单据编号',
                'sale_order_number' => '销售订单号',     //todo 待完善
                'pa_settle_company_name' => '结算单位',
                'sales_manger_name' => '销售人员',
                'create_at' => '日期',
                'invoice_type' => '票据类型',
                'yewu_type' => '业务类型',
                'remark' => '备注',
                'carship_no' => '车船号',
                'status' => '状态',

                'warehouse_name' => '仓库',
                'archive_no' => '钢材编码',
                'archive_name' => '品名',
                'archive_spec' => '规格',
                'archive_material' => '材质',
                'breed_name' => '品种',
                'steel_factory_name' => '钢厂',
                'total_weight' => '重量（吨）',
                'count' => '件数',
                'weight' => '单重',
                'price' => '单价（元）',
                'total_money' => '金额（元）',
                'archive_type' => '码单类型',
                'is_archive_type' => '是否码单',
                'invoice_confirm' => '是否收票',

                'create_at_subsub' => '入库时间',
//                'warehouse_name' => '仓库',   //todo 待完善
//                'archive_name' => '品名',     //todo 待完善
//                'archive_spec' => '规格',     //todo 待完善
//                'archive_material' => '材质', //todo 待完善
                'count_subsub' => '件数',
//                'breed_name' => '品种',       //todo 待完善
//                'steel_factory_name' => '钢厂',   //todo 待完善
                'weight_subsub' => '单重',
                'total_weight_subsub' => '重量（吨）',
                'length' => '长度',
                'stock_num' => '仓位卡号/批号',
                'lockren' => '锁定人',
                'lockriqi' => '锁定日期',
//                'carship_no' => '车/船号',           //todo 待完善
//                'order_sn_code' => '单据号',            //todo 待完善
                'origin' => '产地',
//                'archive_no'=> '钢材编码' , //todo 待完善
                'layer_num' => '层号',
                'price_subsub' => '单价',
                'total_money_subsub' => '金额',
                'pa_contract_no' => '合同号',
                'remark_subsub' => '备注',
            ]
        ];
        $keynum = 0;

        $status_arr = [1 => '待审核', 2 => '审核中', 3 => '审核成功', 4 => '审核失败'];

        $archive_type_arr = [1 => '理计', 2 => '过磅', 3 => '定尺', 4 => '虚拟'];
        foreach ($list['list'] as $k => $v) {
            $keynum += 1;
            $main = [
                'keynum' => $keynum,
                'po_order_sn_code' => $v['po_order_sn_code'],
                'order_sn_code' => $v['order_sn_code'],
                'sale_order_number' => $v['mainorder']['sale_order_number'] ?? '',
                'pa_settle_company_name' => $v['pa_settle_company_name'],
                'sales_manger_name' => $v['sales_manger_name'],
                'create_at' => date('Y-m-d H:i:s', $v['create_at']),
                'invoice_type' => $v['invoice_type'] == 1 ? '专票' : '普票',
                'yewu_type' => '普通业务',
                'remark' => $v['remark'],
                'carship_no' => $v['carship_no'],
                'status' => $status_arr[$v['audit_status']],

                'warehouse_name' => '',
                'archive_no' => '',
                'archive_name' => '',
                'archive_spec' => '',
                'archive_material' => '',
                'breed_name' => '',
                'steel_factory_name' => '',
                'total_weight' => '',
                'count' => '',
                'weight' => '',
                'price' => '',
                'total_money' => '',
                'archive_type' => '',
                'is_archive_type' => '',
                'invoice_confirm' => '',

                'create_at_subsub' => '',
                'count_subsub' => '',
                'weight_subsub' => '',
                'total_weight_subsub' => '',
                'length' => '',
                'stock_num' => '',
                'lockren' => '',
                'lockriqi' => '',
                'origin' => '',
                'layer_num' => '',
                'price_subsub' => '',
                'total_money_subsub' => '',
                'pa_contract_no' => '',
                'remark_subsub' => '',
            ];
            $exceldata[] = $main;
            foreach ($v['suborder'] as $k1 => $v1) {
                $keynum += 1;
                $item = [
                    'keynum' => $keynum,
                    'po_order_sn_code' => $v['po_order_sn_code'],
                    'order_sn_code' => $v['order_sn_code'],
                    'pa_settle_company_name' => $v['pa_settle_company_name'],
                    'sales_manger_name' => $v['sales_manger_name'],
                    'create_at' => date('Y-m-d H:i:s', $v['create_at']),
                    'invoice_type' => $v['invoice_type'] == 1 ? '专票' : '普票',
                    'yewu_type' => '普通业务',
                    'remark' => $v['remark'],
                    'carship_no' => $v['carship_no'],
                    'status' => $status_arr[$v['audit_status']],

                    'warehouse_name' => $v1['warehouse_name'],
                    'archive_no' => $v1['archive_no'],
                    'archive_name' => $v1['archive_name'],
                    'archive_spec' => $v1['archive_spec'],
                    'archive_material' => $v1['archive_material'],
                    'breed_name' => $v1['breed_name'],
                    'steel_factory_name' => $v1['steel_factory_name'],
                    'total_weight' => $v1['total_weight'] / 1000,
                    'count' => $v1['count'],
                    'weight' => $v1['weight'] / 1000,
                    'price' => $v1['price'] / 100,
                    'total_money' => $v1['total_money'] / 100,
                    'archive_type' => $archive_type_arr[$v1['archive_type']],
                    'is_archive_type' => $v1['archive_type'] != 4 ? '是' : '否',
                    'invoice_confirm' => $v1['invoice_confirm'] == 1 ? '否' : '是',

                    'create_at_subsub' => '',
                    'count_subsub' => '',
                    'weight_subsub' => '',
                    'total_weight_subsub' => '',
                    'length' => '',
                    'stock_num' => '',
                    'lockren' => '',
                    'lockriqi' => '',
                    'origin' => '',
                    'layer_num' => '',
                    'price_subsub' => '',
                    'total_money_subsub' => '',
                    'pa_contract_no' => '',
                    'remark_subsub' => '',
                ];
                $exceldata[] = $item;
                foreach ($v1['sub_sub_order'] as $k2 => $v2) {
                    $keynum += 1;
                    $itemitem = [
                        'keynum' => $keynum,
                        'po_order_sn_code' => $v['po_order_sn_code'],
                        'order_sn_code' => $v['order_sn_code'],
                        'pa_settle_company_name' => $v['pa_settle_company_name'],
                        'sales_manger_name' => $v['sales_manger_name'],
                        'create_at' => date('Y-m-d H:i:s', $v['create_at']),
                        'invoice_type' => $v['invoice_type'] == 1 ? '专票' : '普票',
                        'yewu_type' => '普通业务',
                        'remark' => $v['remark'],
                        'carship_no' => $v['carship_no'],
                        'status' => $status_arr[$v['audit_status']],

                        'warehouse_name' => $v1['warehouse_name'],
                        'archive_no' => $v1['archive_no'],
                        'archive_name' => $v1['archive_name'],
                        'archive_spec' => $v1['archive_spec'],
                        'archive_material' => $v1['archive_material'],
                        'breed_name' => $v1['breed_name'],
                        'steel_factory_name' => $v1['steel_factory_name'],
                        'total_weight' => $v1['total_weight'] / 1000,
                        'count' => $v1['count'],
                        'weight' => $v1['weight'] / 1000,
                        'price' => $v1['price'] / 100,
                        'total_money' => $v1['total_money'] / 100,
                        'archive_type' => $archive_type_arr[$v1['archive_type']],
                        'is_archive_type' => $v1['archive_type'] != 4 ? '是' : '否',
                        'invoice_confirm' => $v1['invoice_confirm'] == 1 ? '否' : '是',

                        'create_at_subsub' => $v2['create_at'] ? (is_numeric($v2['create_at']) ? date('Y-m-d H:i:s', $v2['create_at']) : $v2['create_at']) : '',
                        'count_subsub' => $v2['count'],
                        'weight_subsub' => $v2['weight'] / 10000,
                        'total_weight_subsub' => $v2['total_weight'] / 10000,
                        'length' => $v2['length'],
                        'stock_num' => $v2['stock_num'],
                        'lockren' => '',
                        'lockriqi' => '',
                        'origin' => $v2['origin'],
                        'layer_num' => $v2['layer_num'],
                        'price_subsub' => $v2['price'] / 100,
                        'total_money_subsub' => $v2['total_money'] / 100,
                        'pa_contract_no' => $v2['pa_contract_no'],
                        'remark_subsub' => $v2['remark'],
                    ];
                    $exceldata[] = $itemitem;
                }
            }
        }

        $datawith = [];
        $filename = '采购入库单导出.xlsx';
        return Excel::download(new CommonExcelExport($row, $exceldata, $datawith), $filename);
    }
}
